package org.classg.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.classg.order.client.EduClient;
import org.classg.order.client.UcenterClient;
import org.classg.order.entity.Order;
import org.classg.order.mapper.OrderMapper;
import org.classg.order.service.OrderService;
import org.classg.order.utils.OrderNoUtil;
import org.classg.servicebase.exception.MyException;
import org.classg.vo.CourseVo;
import org.classg.vo.UcenterMemberVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 订单 服务实现类
 * </p>
 *
 * @author testjava
 * @since 2020-06-16
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private EduClient eduClient;

    @Autowired
    private UcenterClient ucenterClient;

    // 根据课程id和用户id创建订单，返回订单id
    @Override
    public String insertOrderByCourderIdAndUserId(String courseId, String userId) {
        // （远程调用）根据用户id获取用户信息
        UcenterMemberVo ucenterMemberVo = ucenterClient.queryUserById(userId);
        // （远程调用）根据课程id获取课程信息
        CourseVo courseVo = eduClient.queryCourseById(courseId);

        //创建Order对象，向order对象里面设置需要数据
        Order order = new Order();
        order.setOrderNo(OrderNoUtil.getOrderNo());//订单号
        order.setCourseId(courseId); //课程id
        order.setCourseTitle(courseVo.getTitle());
        order.setCourseCover(courseVo.getCover());
        order.setTeacherName(courseVo.getTeacherName());
        order.setTotalFee(courseVo.getPrice());
        order.setMemberId(userId);
        order.setMobile(ucenterMemberVo.getMobile());
        order.setNickname(ucenterMemberVo.getNickname());
        order.setStatus(0);  //订单状态（0：未支付 1：已支付）
        order.setPayType(1);  //支付类型 ，微信1
        int result = baseMapper.insert(order);
        if (result > 0) {
            return order.getOrderNo();
        } else {
            throw new MyException(20001, "订单创建失败！");
        }
    }

    // 根据订单号查询订单信息
    @Override
    public Order queryOrderByOrderNo(String orderNo) {
        return baseMapper.selectOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNo, orderNo));
    }

}
